package com.teacher.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacher.common.CommonResult;
import com.teacher.common.JwtTokenUtil;
import com.teacher.mapper.DepartmentMapper;
import com.teacher.pojo.entity.Department;
import com.teacher.pojo.entity.PerStudent;
import com.teacher.pojo.entity.PerTeacher;
import com.teacher.pojo.entity.StuClass;
import com.teacher.pojo.vo.department.DepartmentAddVo;
import com.teacher.pojo.vo.department.DepartmentTreeVo;
import com.teacher.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.teacher.service.IPerStudentService;
import com.teacher.service.IPerTeacherService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zfm
 * @since 2021-06-16
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Value("${role.classMonitor}")
    private String classMonitor;

    @Value("${role.admin}")
    private String admin;

    @Value("${role.student}")
    private String student;

    @Value("${role.officeMonitor}")
    private String officeMonitor;

    @Value("${role.office}")
    private String office;

    @Value("${role.subjectMonitor}")
    private String subjectMonitor;

    @Autowired
    private IPerTeacherService iPerTeacherService;

    @Autowired
    private IPerStudentService iPerStudentService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * @param departmentAddVo department's info
     * @return weather success
     */
    @Override
    public CommonResult addDepartment(DepartmentAddVo departmentAddVo) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentAddVo, department);
        // judge whether department's name repeat
        if (baseMapper.selectList(new QueryWrapper<Department>().lambda()
                .eq(Department::getParentId, departmentAddVo.getParentId())
                .eq(Department::getName, department.getName())).size() > 0) {
            return CommonResult.failed("部门名称重复");
        }
        if (baseMapper.insert(department) == 1) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    /**
     * get department by shape of tree
     *
     * @return department's info of shape of tree
     */
    @Override
    public CommonResult getByTree() {
        List<Department> departmentList = baseMapper.selectList(new QueryWrapper<Department>().lambda()
                .orderByDesc(Department::getSort));
        List<DepartmentTreeVo> treeVoList = new ArrayList<>();
        List<DepartmentTreeVo> treeVoEndList = new ArrayList<>();


        for (Department department : departmentList) {
            DepartmentTreeVo departmentTreeVo = new DepartmentTreeVo();
            BeanUtils.copyProperties(department, departmentTreeVo);
            treeVoList.add(departmentTreeVo);
        }

        for (DepartmentTreeVo departmentTreeVo : treeVoList) {
            if (departmentTreeVo.getParentId() == 0 || "0".equals(departmentTreeVo.getParentId())) {
                treeVoEndList.add(departmentTreeVo);
                continue;
            }
            for (DepartmentTreeVo treeVo : treeVoList) {
                System.out.println(JSONUtil.toJsonStr(treeVo));
                if (treeVo.getId().equals(departmentTreeVo.getParentId())) {
                    if (treeVo.getChildList() == null) {
                        treeVo.setChildList(new ArrayList<>());
                    }
                    treeVo.getChildList().add(departmentTreeVo);
                }
            }
        }
        return CommonResult.success(treeVoEndList);
    }

    /**
     * 按照权限查询部门
     *
     * @return
     */
    @Override
    public CommonResult<List<Department>> getByPermission() {
        List<Department> departmentList = new ArrayList<>();
        PerStudent perStudent = iPerStudentService.getOne(new QueryWrapper<PerStudent>().lambda()
                .eq(PerStudent::getStudentKey, jwtTokenUtil.getUsernameByRequest(httpServletRequest)).last("limit 1"));

        // 学生返回空
        if (perStudent != null) {
            return CommonResult.success(departmentList);
        }

        // 不是学生不是老师
        PerTeacher perTeacher = iPerTeacherService.getOne(new QueryWrapper<PerTeacher>().lambda()
                .eq(PerTeacher::getTeacherKey, jwtTokenUtil.getUsernameByRequest(httpServletRequest)).last("limit 1"));
        if (perTeacher == null) {
            return CommonResult.success(departmentList);
        }

        // 是否超级管理员 学工办 学工部主任
        if (perTeacher.getRoleInfo().contains(admin)
                || perTeacher.getRoleInfo().contains(office)
                || perTeacher.getRoleInfo().contains(officeMonitor)) {
            departmentList = this.list(new QueryWrapper<Department>());
            return CommonResult.success(departmentList);
        }

        // 是否专业主任
        if (perTeacher.getRoleInfo().contains(subjectMonitor)) {
            Department department = this.getById(perTeacher.getUpperDept());
            departmentList.add(department);
            return CommonResult.success(departmentList);
        }

        return CommonResult.success(departmentList);
    }
}
